import { App } from './app';
import './dx-ext';
import './qrcode';
import './order';
import './data';
import './product';
import './daily';
import './dealer';

jQuery.extend({
	crudStoreResp: null,

	crudStore: function(url, options) {

		var SERVICE_URL = url;
		options = $.extend({
			onDataArrived: function(data) {
				return data;
			}
		}, options);

		return new DevExpress.data.CustomStore($.extend({}, options, {

			load: function(loadOptions) {

				var u = new Url(SERVICE_URL);

				u.query._param = JSON.stringify(loadOptions);

				return $.getJSON(u).then(function(resp) {
					console.log("data done");
					return options.onDataArrived(resp);
				});
			},

			byKey: function(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.getJSON(u).then(function(resp) {
					return resp.data;
				});
			},

			insert: function(values) {
				return $.post(SERVICE_URL, values).always(function(resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			update: function(key, values) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "PUT",
					data: values,
				}).always(function(resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			remove: function(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "DELETE"
				});
			}

		}));
	},

	crud: function(options) {
		if(typeof(options) === 'object') {
			var app = options.app,
				route = options.route,
				store = jQuery.crudStore(options.url || API(route), options.store);

			options.search = $.extend({
				mobile: 'mobile',
				name: 'uname',
				dateA: 'dateA'
			}, options.search);

			// list

			app.get('#/' + route, function() {
				var eventContext = this,
					capable = $.extend({
						create: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-list").html(), $.extend({}, options, {
					capable: capable
				}))).dxInit();

				var gridType = options.gridType || "dxDataGrid";

				if(options.buttons) {
					$.each(options.buttons, function(i, button) {
						button.instance = $("<div>").dxButton($.extend({
							type: 'normal',
							onClick: function(e) {
								var selections = [];

								if(options.onGetSelectedRowsData) {
									selections = options.onGetSelectedRowsData.call(eventContext, $("#content .crud-grid"));
								} else if(!options.onRenderGrid) {
									selections = $("#content .crud-grid")[gridType]('getSelectedRowsData');
								}

								button.onRoute && button.onRoute.call(eventContext, e.component, selections);
							}
						}, button)).appendTo(
							$("#content .crud-buttons")).dxButton('instance');
					});
				}

				var defaultToolbarItems = [];
				if(options.capable.create) {
					defaultToolbarItems.push('create');
				}

				var toolbarOptions = options.toolbar ? options.toolbar : {
					items: defaultToolbarItems
				};

				$.each(toolbarOptions.items, function(i, item) {
					if(item === 'create') {
						toolbarOptions.items[i] = {
							location: 'before',
							widget: 'dxButton',
							options: {
								text: '新建',
								onClick: function() {
									eventContext.redirect('#/' + route + '/edit');
								}
							}
						};
					}
				});

				console.log(toolbarOptions);
				$("#content .toolbar").dxToolbar(toolbarOptions);

				var ds = new DevExpress.data.DataSource({
					store: store
				});

				if(eventContext.params) {
					$.each(eventContext.params, function(k, v) {
						if(typeof(v) !== 'function' && typeof(v) !== 'object') {
							ds.filter(k, '=', v);
						}
					});
				}

				var param = {
					dataSource: ds,
					allowColumnResizing: true,
					selection: {
						mode: "multiple",
						showCheckBoxesMode: 'always',
						selectAllMode: 'page'
					},
					remoteOperations: true,
					paging: {
						pageSize: 10,
						pageIndex: 0
					},
					onSelectionChanged: function(e) {
						$.each(options.buttons, function(i, button) {
							button.onSelectionChanged &&
								button.onSelectionChanged.call(eventContext, button.instance, e.selectedRowsData, e.component);
						});
					}
				};

				if(options.columns) {
					for(var i = 0; i < options.columns.length; i++) {
						if(options.columns[i].buttons) {

							options.columns[i].cellTemplate = (function(buttons) {
								return function(container, ei) {

									$.each(buttons, function(i, button) {
										var title = button.title,
											url = '#';

										if(button.url) {
											url = Mustache.render(button.url, ei.data);
										}

										var el = $(Mustache.render('<a style="margin: 0 10px;" href="{{url}}">{{title}}</a>', {
											title: title,
											url: url
										}));

										if(button.onClick) {
											el.click(function() {

												button.onClick(ei.data, ei.component);
												return false;
											});
										}

										el.appendTo(container);

										if(button.del) {

											$("<span style='margin:0 5px;vertical-align:1px'>|</span>").appendTo(container)

											$("<a>").text("删除").click(function() {

												DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function(sele) {

													if(sele) {
														var getId = ei.data.id

														$.ajax({
															type: "delete",
															url: $.config('apiUrl') + "restful/" + getId + "?_model=" + button.del
														}).then(function(a) {

															if(a.status = "success") {

																DevExpress.ui.notify({
																	message: function() {

																	let	gridComponent = $("#content .crud-grid").dxDataGrid('instance');

																		gridComponent.option('dataSource').load();

																		return "成功删除";
																	}
																}, "success", 1000)

															} else {

																DevExpress.ui.notify({

																	message: function() {

																		return "操作失败";
																	}
																}, "warning", 1000)
															}
														})
													}
												})
											}).appendTo(container)

										}

									});
								};
							})(options.columns[i].buttons);
						}
					}
					param['columns'] = options.columns;
				}

				if(options.onRenderGrid) {
					options.onRenderGrid.call(eventContext, $("#content .crud-grid"), $.extend({}, param, options.grid));
				} else {
					$("#content .crud-grid")[gridType]($.extend({}, param, options.grid));
				};

				// var gridInst = $("#content .crud-grid")[gridType]("instance");

				if(!options.search['mobile']) $("#content [data-search=mobile]").closest(".input-group").hide();
				if(!options.search['name']) $("#content [data-search=name]").closest(".input-group").hide();
				if(!options.search['lookup']) $("#content [data-search=lookup]").closest(".lookup").hide();
				if(!options.search['mobile'] && !options.search['name']) {
					$("#content .grid-search").hide();
				}

				var now = new Date()
				$("#date").dxDateBox({
					type: "date",
					value: now,
					displayFormat: 'yyyy-MM-dd',
					dateSerializationFormat: "yyyy-MM-dd",
					editorOptions: {
						displayFormat: 'yyyy-MM-dd',
						dateSerializationFormat: 'yyyy-MM-dd'
					}
				})

				$("#content .grid-search").click(function() {
					var name = $("#content [data-search=name]").val(),
						mobile = $("#content [data-search=mobile]").val(),
						dateA = $("#content #date").dxDateBox('option', 'value');

					if(name) {
						ds.searchExpr(options.search['name']);
						$("#content [data-search=mobile]").val('');
					} else if(mobile) {
						ds.searchExpr(options.search['mobile']);
						$("#content [data-search=name]").val('');
					} else if(dateA) {
						ds.searchExpr(options.search['dateA']);
						$("#content #date").dxDateBox('option', 'value');
					}

					ds.searchOperation("contains");
					ds.searchValue(name || mobile || dateA);
					ds.reload();
				});


				// $("#modify_pwd", $(this)).dxDataGrid(param);
				
			});

			function initCrudForm($c, context) {
				var id = context.params.id,
					formOptions = {
						readOnly: false,
						showColonAfterLabel: true,
						showValidationSummary: false,
						colCount: 1,
						validationGroup: "crud",
						items: [],
						onFieldDataChanged: function(e) {
							// console.log("onFieldDataChanged");
							// console.log(e);
						}
					};

				if(id) {
					formOptions.onContentReady = function(e) {
						store.byKey(id).then(function(resp) {

							if(options.form.beforeDataUpdate) {
								options.form.beforeDataUpdate(form, {
									data: resp
								});
							}
							e.component.option('formData', resp);

							if(options.form.afterDataUpdate) {
								options.form.afterDataUpdate(form, {
									data: resp
								});
							}
						});
					}
				}

				var items = [];
				if(options.form && options.form.items) {
					var scene = (id ? 'edit' : 'create');
					$.each(options.form.items, function(i, item) {
						if(item.scene && $.inArray(scene, item.scene) < 0) {

						} else {
							items.push(item);
						}
					});
				}

				var form = $("#form", $c).dxForm($.extend(formOptions, options.form, {
					items: items
				})).dxForm('instance');

				$("#form-container #save", $c).click(function() {
					var result = form.validate();

					if(!result.isValid) {
						var $el = result.validators[0].element();

						var offset = $el.offset();

						$('html, body').animate({
							scrollTop: offset.top - $("header.app-header").height() - 20
						});

					} else {
						$("#form-container", $c).submit();
					}

					return false;
				});

				$("#form-container", $c).on("submit", function(e) {
					var bs = true;
					if(options.form.beforeSubmit) {
						bs = options.form.beforeSubmit(form, id);
					}

					$.when(bs).then(function(result) {
						if(result) {
							if(id) {
								store.update(id, form.option('formData')).then(function(values, resp) {
									DevExpress.ui.notify({
										message: "已更新",
									}, "success", 1000);
									if(options.form.onSaved) {
										options.form.onSaved.call(context, values, resp);
									} else {
										context.redirect('#/' + route);
									}
								}).fail(function() {
									DevExpress.ui.notify({
										message: $.crudStoreResp.message
									}, "warning", 2000);
								});
							} else {
								store.insert(form.option('formData')).then(function(values, resp) {
									if(resp.status == "error") {
										DevExpress.ui.dialog.alert(resp.msg, '提示');
										return false;
									} else {
										DevExpress.ui.notify({
											message: "已完成",
										}, "success", 1000);
										context.redirect('#/' + route);
										//		        						context.redirect('#/' + route + '/edit/' + resp.model.id);
									}
								}).fail(function(resp) {
									DevExpress.ui.notify({
										message: resp,
									}, "warning", 2000);
								});
							}
						}
					})

					return false;
				});

				$("#form-container .delete", $c).click(function() {
					DevExpress.ui.dialog.confirm("确认删除吗?", "请确认").done(function(dialogResult) {
						if(dialogResult) {

							store.remove(id).then(function(resp) {

								DevExpress.ui.notify({
									message: "已删除",
								}, "success", 1000);
								context.redirect("#/" + route);
							});
						}
					});

					return false;
				});

				$("#form-container #cancel").click(function() {
					context.redirect("#/" + route);
					return false;
				});

				var saveNext = false;
				$("#form-container #save").click(function() {
					saveNext = false;
					return false;
				});
				$("#form-container #save-next").click(function() {
					saveNext = true;
					return false;
				});
			}

			// create or edit
			//			console.log("add crud " + route + "/edit");

			app.get('#/' + route + "/edit", function() {
				var eventContext = this,
					capable = $.extend({
						saveNext: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '新建'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});

			//			console.log("add crud " + route + "/edit/:id");

			app.get('#/' + route + "/edit/:id", function() {
				var eventContext = this,
					capable = $.extend({
						delete: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '编辑'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});
		}
	},

	dxCall: function() {
		var comp = $(this).data('dxComponents');
		if(comp && comp.length) {
			var inst = $(this)[comp[0]]("instance");

			return inst[arguments[0]].apply(inst, arguments.slice(1));
		} else {
			return undefined;
		}
	}
});


App.registerCrud({
	route: 'admin-set',
	url: API('restful?_model=sys-seting'),
	title: '系统设置',
	grid: {
		search:{
			mode:'none'
		},
		columnAutoWidth:true,
		showRowLines:true,
		wordWrapEnabled:true
	},
	capable: {
		create: true
	},
	
	columns: [{
		dataField:"label",
		caption:'名称'
	},{
		dataField:'value',
		caption:'参数',
		cellTemplate:function($c,d){
			let values = d.value;
			values = values.split(',');
			$.get($.config('apiUrl')+'simplelist?_model=sys-coupon').then(res =>{
				
				values.forEach((item)=>{
					res.data.forEach((items)=>{
						if(items.id==item){
							let text =$('<div style="width:100%;border-bottom:1px solid #efefef"><div>')
							text.text(items.coupon_name);
							$c.append(text)
						}
					})
				})

				
			})
			
		}
	},{
		dataField:'updated_at',
		caption:'更新时间'
	},{
		caption:'操作',
		buttons:[{
			title:'编辑',
			onClick:function(data,instance){
				$.get($.config('apiUrl')+'simplelist?_model=sys-coupon').then(res =>{
			$('<div>').appendTo('#popups').dxPopup({
				width:1000,
				height:600,
				visible:true,
				onContentReady:function(e){
					var $content = e.component.content();
					let values = data.value;
					values = values.split(',');	

					let instance = '';
				
					$content.find('.popup_button').dxToolbar({
						items:[{
							location:'before',
							widget:"dxButton",
							options:{
								text:'保存',
								onClick:function(){
									console.log(data);
									let test =[];
									$.each(values,(te,ist) =>{
										if(Number(ist) != 0){
											test.push(ist)
										}
									})
									values = test;
									test =test.join(',');
									$.ajax({
										type:'PUT',
										url:$.config('apiUrl')+`restful/${data.id}?_model=sys-seting`,
										data:{
											value:test,
											key:data.key
										},
										success:function(resp){
											if(resp.status == 'success'){
												DevExpress.ui.notify('修改成功','success',1500);
												$('#popups').find('div').remove();
												App.crudGridInstance().option('dataSource').reload()
											}else{
												DevExpress.ui.notify('修改失败：'+resp.messagem,'warning',1500)
											}
										},
										error:function(){
											DevExpress.ui.notify('未知错误','warning',1500)
										}
									})
								}
							}
						},{
							location:'after',
							widget:"dxButton",
							options:{
								text:'增加',
								onClick:function(){
									values.push(0);
									instance();
								}
							}
						}]
					})

					instance=function(){
						$content.find('.popup_content').html('');
						let $html =$('<div></div>');
						$.each(values,(i,item)=>{
								let names = $('<div class="row"><div style="margin-bottom:20px" class=" pull-left col-sm-10"><div class="popup_select"></div></div><div class="pull-right col-sm-2" ><div class="popup_delete"></div></div></div>')
								names.find('.popup_select').dxSelectBox({
									dataSource:res.data,
									valueExpr:'id',
									value:Number(item),
									displayExpr:"coupon_name",
									itemTemplate:function(data, index, $el){
										if (data) {
                      $("<span>" + data.name+' - '+data.coupon_name + "</span>").appendTo($el);
                    }
									},
									onValueChanged:function(ev){
										let val = ev.value;
										values[i]=Number(val)
									}
								})
								names.find('.popup_delete').dxButton({
									text:'删除',
									onClick:function(){
										values.splice(i,1);
										instance()
									}
								})
							$html.append(names)	
					
						
					});

					$content.find('.popup_content').append($html);

					}

					instance()

				},
				contentTemplate:function(){
				let	$html = $('<div class="popup_container"><div class="popup_content"></div><div class="popup_button"></div></div>')
					return $html
				}

			})
		})
			}
		}]
	}
	]

});



App.registerCrud({
	route: 'product',
	url: API('restful?_model=wine-product'),
	title: '产品',
	grid: {
		columnAutoWidth:true,
		showRowLines:true,
		wordWrapEnabled:true
	},
	placeholder: '红酒名称',
	capable: {
		create: true
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '新建',
				onClick: function() {
					App.getEventContext().redirect('#/newproduct');
				}
			}
		}]
	},
	search: {
		mobile: 'nickname',
	},
	columns: [{
			dataField: 'id',
			caption: 'id'
		}, {
			dataField: 'chname',
			caption: '葡萄酒名称'
		}, {
			dataField: 'weight',
			caption: '权重',
			cellTemplate: function(con, da) {
				$(con).dxWeight("product", da)
			}
		}, {
			dataField: 'promotion_price',
			caption: '促销价'
		}, {
			dataField: 'sku',
			caption: '库存',
			cellTemplate: function(con, opt) {
				$(con).dxsetsku('product', opt)
			}
		}, {
			dataField: 'online',
			caption: '上下线',
			cellTemplate: function(con, opt) {
				$(con).dxUpdown('product', opt)

			}
		}, {
			minWidth: 100,
			caption: '操作',
			buttons: [{
				title: '编辑',
				url: '#/newproduct/{{id}}',
				del: 'wine-product'
			}]

		},
		{
			caption: '预览',
			buttons: [{
				title: "预览"
			}]
		}, {
			dataField: 'pv',
			caption: 'pv'
		}, {
			dataField: 'uv',
			caption: 'uv'
		}, {
			dataField: 'want_drink_count',
			caption: '想喝'
		}, {
			dataField: 'has_drink_count',
			caption: '喝过'
		}, {
			dataField: 'order_count',
			minWidth: 100,
			caption: '订单量'
		}
	]

});
App.registerCrud({
	route: 'product-drink',
	url: API('restful?_model=wine-product-drink'),
	title: 'Drink介绍',
	placeholder: '昵称',
	capable: {
		create: false
	},
	search: {
		mobile: 'nickname',
	},
	columns: [{
		dataField: 'avatar',
		caption: '会员头像',
		allowFiltering: false,
		allowSorting: false,
		cssClass: 'avatarImg',
		cellTemplate: function(container, options) {
			$("<div>").append($("<img>", {
				"src": options.value
			})).appendTo(container);
		}
	}, {
		dataField: 'nickname',
		caption: '会员昵称'
	}, {
		dataField: 'username',
		caption: '会员姓名'
	}, {
		dataField: 'point',
		caption: '会员积分'
	}, {
		minWidth: 120,
		caption: '操作',
		buttons: [{
			title: '查看',
			url: '#/integral-details/{{id}}'
		}]
	}]
});

App.registerCrud({
	route: 'product-judge',
	url: API('restful?_model=wine-product-judge'),
	title: '专业品鉴',
	placeholder: '昵称',
	capable: {
		create: false
	},
	search: {
		mobile: 'nickname',
	},
	columns: [{
		dataField: 'avatar',
		caption: '会员头像',
		allowFiltering: false,
		allowSorting: false,
		cssClass: 'avatarImg',
		cellTemplate: function(container, options) {
			$("<div>").append($("<img>", {
				"src": options.value
			})).appendTo(container);
		}
	}, {
		dataField: 'nickname',
		caption: '会员昵称'
	}, {
		dataField: 'mobile',
		caption: '手机号'
	}, {
		dataField: 'email',
		caption: '邮箱'
	}, {
		dataField: 'publish_project_count',
		caption: '项目发布数量'
	}, {
		dataField: 'execute_project_count',
		caption: '项目执行数量'
	}, {
		dataField: 'rank',
		caption: '评分'
	}, {
		caption: '操作',
		buttons: [{
			title: '查看',
			url: '#/score-details/{{id}}'
		}]
	}]
});

App.registerCrud({
	route: 'product-technique',
	url: API('restful?_model=win-product-technique'),
	title: '技术信息',
	placeholder: '昵称',
	capable: {
		delete: false,
		create: false
	},
	search: {
		mobile: 'nickname',
	},
	columns: [{
		dataField: 'avatar',
		caption: '会员头像',
		allowFiltering: false,
		allowSorting: false,
		cssClass: 'avatarImg',
		cellTemplate: function(container, options) {
			$("<div>").append($("<img>", {
				"src": options.value
			})).appendTo(container);
		}
	}, {
		dataField: 'nickname',
		caption: '会员昵称'
	}, {
		dataField: 'email',
		caption: '邮件地址'
	}, {
		dataField: 'mobile',
		caption: '手机号'
	}, {
		dataField: 'username',
		caption: '会员姓名'
	}, {
		dataField: 'id_card',
		caption: '身份证'
	}, {
		dataField: 'is_publish',
		caption: '需求录入创客'
	}, {
		dataField: 'is_execute',
		caption: '任务执行创客'
	}, {
		dataField: 'is_manager',
		caption: '项目经理'
	}, {
		dataField: 'created_at',
		caption: '加入时间'
	}, {
		dataField: 'linkman_count',
		caption: '联系人',
		tellTemplate: function(container, options) {
			$("<div>").text(options.data.linkman_count).appendTo(container)
		}
	}, {
		minWidth: 120,
		caption: '操作',
		buttons: [{
			title: '配置权限',
			url: '#/vip_authority/{{id}}'
		}]
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items: [{
			itemType: "group",
			items: [{
				dataField: "mobile",
				label: {
					text: '会员手机'
				},
				validationRules: [{
					type: "required",
					message: "请输入会员手机号"
				}, {
					type: "pattern",
					pattern: /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/,
					message: "手机号格式错误"
				}]
			}, {
				dataField: "username",
				label: {
					text: '会员姓名'
				},
			}, {
				dataField: "identity_card",
				label: {
					text: '会员证件号'
				},
			}, {
				dataField: "remark",
				editorType: "dxTextArea",
				label: {
					text: '备注'
				},
				editorOptions: {
					height: 140
				}
			}]
		}]
	}
});

App.registerCrud({
	route: 'product-score',
	url: API('restful?_model=wine-product-score'),
	title: '专业评分',
	capable: {
		create: false
	},
	search: {
		mobile: false,
		lookup: true,
		dateA: 'dividend_date'
	},
	columns: [{
		dataField: 'dividend_date',
		caption: '分红日期',
		sortOrder: 'desc'
	}, {
		dataField: 'user_count',
		caption: '分红用户数'
	}, {
		dataField: 'partake_total',
		caption: '参与分红总金额（万元）',
		format: function(v) {
			return parseFloat(v).toFixed(2);
		}
	}, {
		dataField: 'plan_price',
		caption: '分红金额/万元',
		format: function(v) {
			return parseFloat(v).toFixed(2);
		}
	}, {
		dataField: 'dividend_total',
		caption: '分红总金额',
		format: function(v) {
			return parseFloat(v).toFixed(2);
		}
	}]
});

App.registerCrud({
	url: API('restful?_model=wine-chateau'),
	route: 'chateau',
	title: '酒庄',
	capable: {
		create: true
	},
	columns: [{
			dataField: 'id',
			caption: 'id'
		}, {
			dataField: 'chname',
			caption: '酒庄名称'
		},
		{
			dataField: 'weight',
			caption: '权重',
			cellTemplate: function(con, da) {
				con.dxWeight('chateau', da)
			}
		},
		{
			dataField: 'online',
			caption: '上下线',
			cellTemplate: function(con, da) {
				con.dxUpdown('chateau', da)
			}
		},
		{
			caption: "操作",
			buttons: [{
				title: '编辑',
				url: '#/chateau/edit/{{id}}',
				del: 'wine-chateau'
			}]
		}
	],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		afterDataUpdate: function(formInstance, data) {
			//console.log(formInstance.geiEditor("#editor"));

		},
		beforeSubmit: function(form, id) {
			var formData = form.option('formData');

			formData.state = 'publish';

			form.option('formData', formData);

			function pic(data) {
				var chateau = [];
				if(data && data.length > 0) {
					$.each(data, function(er, da) {
						chateau.push(da.id);
					});
				};
				return chateau.join()
			};
			formData.master_pic_ids = pic(formData.chateau_master_pic);
			formData.pic_ids = pic(formData.chateau_pic);
			formData.grapery_pic_ids = pic(formData.chateau_grapery_pic);
			console.log(formData)
			return true;
		},

		items: [{
			itemType: "group",

			items: [{
					dataField: 'chateauCode',
					label: {
						text: '酒庄编码'
					},
					validationRules: [{
						type: "required",
						message: "请输入酒庄编码"
					}, {
						type: 'pattern',
						pattern: /^[A-Z0-9]{2,5}$/,
						message: '酒庄编码必须是5位以内的大写字母或数字组合'
					}],
					editorType: "dxTextBox",
					helpText: '5位以内的大写字母或数字组合（至少2位）'
				}, {
					dataField: "chname",
					validationRules: [{
						type: "required",
						message: "请输入中文名称"
					}],
					label: {
						text: '中文名称'
					}
				}, {
					dataField: "name",
					validationRules: [{
						type: "required",
						message: "请输入中文名称"
					}],
					label: {
						text: '英文名称'
					}
				}, {
					dataField: "chateau_pic",
					validationRules: [{
						type: "required",
						message: "封面图片"
					}],
					editorType: "ImageUploader",
					editorOptions: {
						imageWidth: 750,
						imageHeight: 838
					},
					label: {
						text: '封面图片'
					}

				},
				{
					dataField: 'produce_id',
					validationRules: [{
						type: "required",
						message: "请输入生产商"
					}],
					label: {
						text: '生产商'
					},
					editorType: 'dxSelectBox',
					editorOptions: {
						dataSource: $.crudStore(API('restful?_model=sys-produce')),
						showClearButton: true,
						placeholder: "生产商",
						searchEnabled: true,
						valueExpr: 'id',
						noDataText: '没有请求到生产商数据',
						itemTemplate: function(data, index, $el) {
							if(data) {
								$("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
							}
						},
						displayExpr: function(data) {
							return data ? data.chname + " (" + data.name + ")" : "";
						}
					},

				},
				{
					dataField: "address",
					validationRules: [{
						type: "required",
						message: "请输入地址"
					}],
					label: {
						text: '地址'
					}
				}, {
					dataField: "levelType",
					label: {
						text: '酒庄评级系统'
					}

				}, {
					dataField: "website",
					label: {
						text: '官网链接'
					}
				},
				{
					dataField: 'intro',
					validationRules: [{
						type: "required",
						message: "请输入酒庄介绍"
					}],
					editorType: 'dxEditor',
					label: {
						text: '酒庄介绍'
					}
				},
				{
					dataField: "feature",
					validationRules: [{
						type: "required",
						message: "请输入酒庄特点"
					}],
					label: {
						text: "酒庄特点"
					},
					editorType: 'dxEditor'
				},
				{
					dataField: 'chateau_master_pic',
					label: {
						text: "庄主照片"
					},
					editorType: 'ImageUploader',
					editorOptions: {
						imageWidth: 750,
						imageHeight: 422
					}
				},
				{
					dataField: 'owner',
					label: {
						text: '庄主姓名'
					}
				},
				{
					dataField: 'owner_intro',
					label: {
						text: '庄主介绍'
					},
					editorType: "dxTextArea",
					editorOptions: {
						height: 120
					}
				},
				{
					dataField: "area",
					label: {
						text: '葡萄园面积'
					}
				},
				{
					dataField: 'chateau_grapery_pic',
					label: {
						text: "葡萄园图片"
					},
					editorType: "ImageUploader",
					editorOptions: {
						imageWidth: 750,
						imageHeight: 422
					}
				},
				{
					dataField: 'chateau_grapery',
					label: {
						text: ' ',
						showColon: false
					},
					editorType: 'GrapeList'
					//占位
				},
				{
					dataField: "age",
					label: {
						text: '平均树龄'
					}
				},
				{
					dataField: "soil",
					label: {
						text: "土壤类型"
					},
					editorType: "dxTextArea",
					editorOptions: {
						autoResizeEnabled: true
					}
				},
				{
					dataField: 'harvest',
					label: {
						text: "采收方式"
					},
					editorType: 'dxTextArea',
					editorOptions: {
						autoResizeEnabled: true
					}
				}
			]
		}]
	}

});


App.registerCrud({
	route: 'restful',
	url: API('restful?_model=cms-article'),
	title: '文章',
	placeholder: '文章名称',
	capable: {
		create: true
	},
	search: {
		mobile: 'title'
	},
	toolbar: {
		items: ['create', {
			location: 'after',
			widget: 'dxSelectBox',
			options: {
				width: 150,
				dataSource: $.crudStore(API('restful?_model=cms-article-column')),
				valueExpr: 'id',
				displayExpr: 'name',
				showClearButton: true,
				placeholder: '按文章分类',
				onValueChanged: function(e) {
					var ds = App.crudGridInstance().option('dataSource');

					if(e.value) ds.filter('column_id', '=', e.value);
					else ds.filter(null);

					ds.reload();
				}
			}
		}]
	},
	columns: [{
		dataField: 'id',
		caption: 'id'
	}, {
		dataField: 'title',
		caption: '文章名称'
	}, {
		dataField: 'column_name',
		caption: '栏目'
	}, {
		dataField: 'weight',
		caption: '权重',
		cellTemplate: function(con, dat) {
			$(con).dxWeight('article', dat)
		}
	}, {
		dataField: 'online',
		caption: '上下线',
		cellTemplate: function(con, dat) {

			$(con).dxUpdown('article', dat)
		}
	}, {
		dataField: "content",
		caption: '操作',
		buttons: [{
			title: '编辑',
			url: '#/restful/edit/{{id}}',
			del: 'cms-article'
		}]
	}, {
		dataField: 'pv',
		caption: 'PV'
	}, {
		dataField: 'uv',
		caption: 'UV'
	}, {
		dataField: 'collection_quantity',
		caption: '收藏量'
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		beforeDataUpdate: function(formInstance, data) {
			if(data.data.column_id) {
				data.data.column_id = parseInt(data.data.column_id);
			}

			data.data.column = undefined;
		},
		afterDataUpdate: function(formInstance, data) {
			//console.log(formInstance.geiEditor("#editor"));

		},
		beforeSubmit: function(form, id) {
			var formData = form.option('formData');

			formData.video_type = 'url';
			if(!formData.covers){
				DevExpress.ui.notify('请上传封面图片','warning',1500)
				return false
			}
			var cover = [];
			$.each(formData.covers, function(i, cov) {
				cover.push(cov.id)
			});
			if(cover.length == 0) {
				formData.cover_ids = 0;
			} else {
				formData.cover_ids = cover.join()
			};

			formData.state = 'publish';

			form.option('formData', formData);
			return true;
		},
		items: [{
				label: {
					text: '文章'
				},
				editorType: 'dxRadioGroup',
				dataField: 'type',
				editorOptions: {
					layout: "horizontal",
					items: [{
						text: '文章',
						value: 'article'
					}, {
						text: '视频',
						value: 'video'
					}],
					valueExpr: 'value',
					onValueChanged: function(e) {
						var formInstance = e.element.closest(".dx-form").dxForm("instance");

						if(e.value === 'article') {
							formInstance.getEditor('video_path').element().closest(".dx-field-item").addClass("hidden");
							formInstance.getEditor('content').element().closest(".dx-field-item").removeClass("hidden");
						} else {
							formInstance.getEditor('video_path').element().closest(".dx-field-item").removeClass("hidden");
							formInstance.getEditor('content').element().closest(".dx-field-item").addClass("hidden");
						}
					}
				}
			}, {
				label: {
					text: '列表方式'
				},
				editorType: 'dxRadioGroup',
				dataField: 'feature',
				validationRules: [{
					type: "required"
				}],
				editorOptions: {
					layout: "horizontal",
					items: [{
						text: '大图',
						value: 1
					}, {
						text: '小图',
						value: 0
					}],
					value:1,
					valueExpr: 'value',
				}
			}, {
				dataField: "title",
				validationRules: [{
					type: "required"
				}],
				label: {
					text: '文章名称'
				}
			}, {
				dataField: "author",
				label: {
					text: '作者'
				}
			}, {
				dataField: "column_id",
				validationRules: [{
					type: "required"
				}],
				label: {
					text: '栏目'
				},
				editorType: 'dxSelectBox',
				editorOptions: {
					dataSource: $.crudStore(API('restful?_model=cms-article-column')),
					showClearButton: true,
					placeholder: "分类",
					searchEnabled: true,
					valueExpr: 'id',
					displayExpr: 'name',
					noDataText: '没有请求到分类数据',
					deferRendering: false,
					itemTemplate: function(data) {
						return data.name
					}
				}

			}, {
				dataField: "abstract",
				label: {
					text: '摘要'
				}
			},
			{
				dataField: "covers",
				name: "name",
				editorType: "ImageUploader",
				label: {
					text: '封面图片'
				},
				editorOptions: {
					imageWidth: 750,
					imageHeight: 480
				}

			},
			{
				dataField: 'content',
				label: {
					text: '文章正文'
				},
				editorType: 'dxEditor'
			},
			{
				dataField: 'video_path',
				editorType: 'VideoUploader',
				label: {
					text: '视频'
				},
				cssClass: 'hidden'
			}
		]
	}
});

function activity_order(ID){
	let logistics={
				id:ID,
				express_name:'',
				express_number:''
			}
				$("<div/>").appendTo($("#popups")).dxPopup({
					title:'请输入',
					visible:true,
					width:450,
					height:360,
					contentTemplate:function(){
						let html = "<form class='is_delivery' style='width:100%''><div class='corporation' style='margin-bottom:20px'></div><div class='product_order' style='margin-bottom:20px;text-align:center'></div><div class='order_button' ></div></form>"
						return html
					},
					onContentReady:function(e){
						console.log(e)
						let $content = e.component.content();
						$content.find(".corporation").dxSelectBox({
							placeholder:"物流公司",
							validationRules: [{
							type: "required"
								}],
							showClearButton:true,
							searchEnabled:true,
							dataSource:$.crudStore(API('restful?_model=express-carrier')),
							displayExpr:'name_cn',
							valueExpr:'code',
							onValueChanged:function(e){
								logistics.express_name=e.value;
							}
						});
						$content.find('.product_order').dxTextBox({
							placeholder:'物流单号',
							validationRules: [{
							type: "required"
								}],
							value:'',
							onInput:function(e){
								logistics.express_number=e.component._options.text
							},
							onFocusOut:function(e){
								logistics.express_number=e.component._options.text
							}
						});
						$content.find(".order_button").dxButton({
							text:'发货',
							type:'success',
							onClick:function(e){
								$.post(API('activity-order/delivery'),
								logistics,
								function(e){
									DevExpress.ui.notify('发货成功','success',1500) ;
									App.crudGridInstance().option('dataSource').load()

								});
								return false
							}
						})
					}
				})
			};



App.registerCrud({
	route: 'activity_order',
	url: API('restful?_model=activity-order'),
	title: '活动订单',
	capable: {
		create: false
	},
	grid: {
		selection: {
			mode: 'none'
		},
		columnAutoWidth:true,
		showRowLines:true,
		wordWrapEnabled:true
	},
	columns: [{
		dataField: 'id',
		caption: 'id'
	}, {
		dataField:'activity_name',
		caption:'活动名称',
		width:200
	},{
		dataField: 'name',
		caption: '姓名'
	}, {
		dataField: 'mobile',
		caption: '联系方式'
	}, {
		dataField: 'location',
		caption: '地址'
		
	},{
		dataField:'apply_rule',
		caption:'申请条件'
	},{
		dataField: 'apply_state',
		caption: '申请情况',
		cellTemplate:function($c,d){
			let value = Number(d.value);
			let text =''
			if(value){
				text='已申请'
			};
			$c.text(text)
		}
	},{
		dataField:'apply_pass_time',
		caption:'助力完成时间'
	},{
		dataField: 'old',
		caption: '分享老用户'
	},{
		dataField: 'new',
		caption: '分享新用户'
	},{
		dataField: 'state',
		caption: '操作',
		cellTemplate:function($c,d){
			let value = Number(d.value);
			let pass = '',text=''

			if(value == 6){
				return $c.text('活动结束')
			}

			if(value>=3&&value<8){
				return $c.text('已通过')
			};

			if(value==0){
				return $c.text('未通过')
			};

			if(value == 3&& false){
				text='通过';pass='unpass'
			}

			if(value<3){
				text='未通过';pass='pass'
			}
		$('<a>').text(text).css('text-decoration','undreline').click(function(){
			$.post($.config('apiUrl')+`activity-order/${d.row.data.id}/changeState`,{state:pass}).always(res =>{
				console.log()
				if(res.status=='success'){
									DevExpress.ui.notify('保存成功','success',1500);
									App.crudGridInstance().option('dataSource').load()
								}else{
									DevExpress.ui.notify('保存失败：'+res.responseJSON.message,'warning',1500);
								}
			})
		}).appendTo($c)	
		}
	},{
		dataField:'state',
		caption:"状态",
		cellTemplate:function($c,d){
			console.log(d)
			let value = Number(d.value);
			let text =''
			switch(value){
				case 3:text='发货';break;
				case 4:text='已发货';break;
				case 5:text='已发货';break;
				case 7:text='完成反馈,查看';break;
			}
			if(value==3){
				$('<a>').text(text).click(function(){
					activity_order(d.row.data.id)
				}).appendTo($c)
				return 
			};
			$c.text(text)
		}
	}]
});

App.registerCrud({
	route: 'article-column',
	url: API('restful?_model=cms-article-column'),
	title: '文章分类',
	capable: {
		create: true
	},
	columns: [{
		dataField: 'name',
		caption: '栏目名称',
		minWidth: 150
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		dataField: 'updated_at',
		caption: '最近修改'
	}, {
		caption: '操作',
		buttons: [{
			title: '编辑',
			url: '#/article-column/edit/{{id}}',
			del: 'cms-article-column'
		}]
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items: [{
			dataField: 'name',
			label: {
				text: '栏目名称'
			},
			validationRules: [{
				type: "required"
			}],
		}]
	}
});


function activity_list(ID){
	let nextid = ''
				$("<div/>").appendTo($("#popups")).dxPopup({
					title:'请选择活动',
					visible:true,
					width:450,
					height:360,
					contentTemplate:function(){
						let html = "<form class='is_delivery' style='width:100%''><div class='corporation' style='margin-bottom:20px'></div><div class='order_button' ></div></form>"
						return html
					},
					onContentReady:function(e){
						console.log(e)
						let $content = e.component.content();
						$content.find(".corporation").dxSelectBox({
							placeholder:"选择活动",
							validationRules: [{
							type: "required"
								}],
							showClearButton:true,
							searchEnabled:true,
							dataSource:$.crudStore(API(`activity/${ID}/next/list`)),
							displayExpr:'name',
							valueExpr:'id',
							onValueChanged:function(e){
								nextid=e.value;
							}
						});
						
						$content.find(".order_button").dxButton({
							text:'保存',
							type:'success',
							onClick:function(e){
								$.post(API(`activity/${ID}/${nextid}`),
								{},
								function(e){
									DevExpress.ui.notify('保存成功','success',1500) ;
									App.crudGridInstance().option('dataSource').load()
									$('#popups').find('div').remove();
								});
								return false
							}
						})
					}
				})
			};

App.registerCrud({
	route: 'activity_list',
	url: API('restful?_model=activity'),
	title: '活动',
	capable: {
		create: true
	},
	grid: {
		selection: {
			mode: 'none'
		}
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '新建',
				onClick: function() {
					App.getEventContext().redirect('#/activity?id=NEW');
				}
			}
		}]
	},
	columns: [{
		dataField: 'id',
		caption: 'id'
	},{
		dataField: 'name',
		caption: '活动主题',
		width:280
	}, {
		dataField: 'type',
		caption: '分类',
		width:80,
		cellTemplate:function($c,d){
			let text = d.value=='article'?'文章':'海报';
			$c.text(text)
		}
	}, {
		dataField:'start_time',
		caption:'开始时间'
	}, {
		dataField:'end_time',
		caption:'结束时间'
	},{
		dataField:'deadline',
		caption:'报名截止时间'
	},{
		dataField:'id',
		caption:'设置下一弹',
		cellTemplate:function($c,e){
			let ID = e.value;
			let name = e.row.data.next_activity
			$('<a>').text(name?name.name:'点击设置').click(function(){
				activity_list(ID)
			}).appendTo($c)
		}
	}, {
		dataField: 'id',
		caption: '操作',
		width:80,
		cellTemplate:function($c,d){
			$('<a>').text('查看').click(function(){
				App.getEventContext().redirect('#/activity?id='+d.value)
			}).appendTo($c)
		}
	},{
		dataField: 'participate_limit',
		caption: '活动人数'
	},{
		dataField: 'sign_count',
		caption: '已报名人数'
	},{
		dataField: 'click_count',
		caption: '点击量'
	},{
		dataField: 'collect_count',
		caption: '收藏量'
	}]
});

// App.registerCrud({
// 	route: 'article-column',
// 	url: API('restful?_model=cms-article-column'),
// 	title: '文章分类',
// 	capable: {
// 		create: true
// 	},
// 	columns: [{
// 		dataField: 'name',
// 		caption: '栏目名称',
// 		minWidth: 150
// 	}, {
// 		dataField: 'created_at',
// 		caption: '创建时间'
// 	}, {
// 		dataField: 'updated_at',
// 		caption: '最近修改'
// 	}, {
// 		caption: '操作',
// 		buttons: [{
// 			title: '编辑',
// 			url: '#/article-column/edit/{{id}}',
// 			del: 'cms-article-column'
// 		}]
// 	}],
// 	form: {
// 		readOnly: false,
// 		showColonAfterLabel: true,
// 		showValidationSummary: false,
// 		colCount: 1,
// 		items: [{
// 			dataField: 'name',
// 			label: {
// 				text: '栏目名称'
// 			},
// 			validationRules: [{
// 				type: "required"
// 			}],
// 		}]
// 	}
// });

App.registerCrud({
	url: API('restful?_model=sys-admin'),
	route: 'admin-users',
	title: '系统管理员',
	placeholder: '会员名',
	capable: {
		create: true
	},
	buttons: [{
		text: '删除',
		type: 'danger',
		disabled: true,
		onSelectionChanged: function(component, selections, gridComponent) {
			component.option('disabled', selections.length <= 0);
		},
		onClick: function() {
			var store = $.crudStore(API("admin")),
				gridComponent = $("#content .crud-grid").dxDataGrid('instance'),
				selections = gridComponent.getSelectedRowsData(),
				ids = $.map(selections, function(item) {
					return item.id;
				}).join(",");

			DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function(dialogResult) {
				if(dialogResult) {
					store.remove(ids).then(function(resp) {

						DevExpress.ui.notify({
							message: "已删除",
						}, "success", 1000);
						gridComponent.option('dataSource').load();
					});
				}
			});
			return false;
		}
	}],
	columns: [{
		dataField: 'name',
		caption: '名称'
	}, {
		dataField: 'account',
		caption: '账号'
	}, {
		dataField:'userType',
		caption:'权限',
		cellTemplate:function($c,d){
		
			var text = '';
			if(d.value == 'admin'){
			text = '管理员'
			}else if(d.value == 'editor'){
				text = '录入员'
			};
			$c.text(text)
		}
	},{
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		caption: '操作',
		buttons: [{
			title: '编辑',
			url: '#/admin-users/edit/{{id}}'
		}, {
			title: '更改密码',
			url: '#/admin-users/password/edit/{{id}}'
		}, {
			title: '删除',
			onClick: function(data) {
				DevExpress.ui.dialog.confirm("确定删除 " + data.account + " 吗?", "请确认").done(function(dialogResult) {
					if(dialogResult) {
						var ds = App.crudGridInstance().option('dataSource');
						ds.store().remove(data.id).then(function(resp) {
							DevExpress.ui.notify({
								message: "已删除",
							}, "success", 1000);
							ds.reload();
						});
					}
				});
			}
		}]
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items: [{
			dataField: 'name',
			label: {
				text: '名称'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'account',
			label: {
				text: '帐号'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			scene: ['create'],
			dataField: 'password',
			label: {
				text: '密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			scene: ['create'],
			dataField: 'password_confirmation',
			label: {
				text: '确认密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField:'userType',
			editorType:'dxSelectBox',
			label:{text:'权限'},
			validationRules: [{
				type: "required"
			}],
			editorOptions:{
				dataSource:[{name:'管理员',value:'admin'},{name:'产品录入员',value:'editor'}],
				displayExpr:'name',
				valueExpr:"value",
				onValueChanged:function(e){
					App.getFormInstance().option('formData.userType',e.value)
				}
			}
		},{
			label: {
				text: '允许访问ip段'
			}
		}, {
			dataField: 'ip_min',
			label: {
				text: '最小值'
			}
		}, {
			dataField: 'ip_max',
			label: {
				text: '最大值'
			}
		}]
	}
});



App.registerCrud({
	url: API('restful?_model=sys-admin'),
	route: 'admin-users/password',
	title: '更改密码',
	capable: {
		create: false,
		delete: false
	},
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		onSaved: function() {
			this.redirect("#/admin-users");
		},
		items: [{
			dataField: 'name',
			label: {
				text: '用户名'
			},
			validationRules: [{
				type: "required"
			}],
			editorOptions: {
				readOnly: true
			}
		}, {
			dataField: 'account',
			label: {
				text: '帐号'
			},
			validationRules: [{
				type: "required"
			}],
			editorOptions: {
				readOnly: true
			}
		}, {
			dataField: 'password',
			label: {
				text: '密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'password_confirmation',
			label: {
				text: '确认密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}]
	}
});

App.registerCrud({
	url: API('restful?_model=user'),
	route: 'user_list',
	title: '用户',
	capable: {
		create: false,
		delete: false
	},
	search:{
		mobile:'mobile',
		name:'name'
	},
	grid:{
		selection: {
			mode: 'none'
		}
	},
	columns: [{
		dataField: 'id',
		caption: 'id',
		width:80
	}, {
		dataField: 'name',
		caption: '姓名',
		width:200
	}, {
		dataField: 'mobile',
		caption: '联系方式',
		width:150
	}, {
		dataField: 'intro',
		caption: '介绍',
		width:280
	}, {
		dataField: 'id',
		caption: '标签',
		cellTemplate:function($c,d){
			$c.text('长得好看')
		}
	}, {
		dataField: 'activity_count',
		caption: '活动参与次数'
	}, {
		dataField: 'order_count',
		caption: '产品购买次数'
	}]
});


App.registerCrud({
	route: 'area-manage',
	title: '区域',
	columns: [{
		dataField: 'YQXMC',
		caption: '区域名称'
	}, {
		dataField: 'SSMC',
		caption: '上级区域'
	}, {
		dataField: 'id',
		caption: '更新时间'
	}, {
		caption: '操作',
		buttons: [{
			title: '编辑',
			url: ''
		}]
	}]
});


App.registerCrud({
	url: API('restful?_model=sys-country'),
	route: 'country',
	title: '国家',
	capable: {
		create: true
	},
	search: {
		mobile: 'chCountry',
		name: '国家名称'
	},

	columns: [{
			dataField: 'id',
			caption: 'id'
		}, {
			dataField: 'chCountry',
			caption: '国家中文名称'
		}, {
			dataField: 'country',
			caption: '国家英文名称'
		}, {
			dataField: 'countryCode',
			caption: '国家代码'
		}, {
			dataField: 'national_flag',
			caption: '国旗',
			cellTemplate: function(container, data) {
				$("<img>").css({
					"width": "80px"
				}).attr("src", data.data['national_flag']).appendTo(container)
			}
		},
		{
			caption: '操作',
			buttons: [{
				title: '编辑',
				url: '#/country/edit/{{id}}',
				del: 'sys-country'
			}]
		}
	],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items: [{
			dataField: 'chCountry',
			label: {
				text: '中文名称'
			}
		}, {
			dataField: 'country',
			label: {
				text: '英文名称'
			}
		}, {
			dataField: 'countryCode',
			label: {
				text: '国家代码'
			}
		}, {
			dataField: 'national_flag',
			label: {
				text: '国旗'
			},
			editorType: 'ImageUploader',
			editorOptions: {
				single: true
			}
		}]
	}
});


App.registerCrud({
	url: API('restful?_model=expert-user'),
	route: 'expert-user',
	title: '专家',
	capable: {
		create: true
	},
	search: {
		mobile: false
	},
	columns: [{
			dataField: 'id',
			caption: 'id'
		}, {
			dataField: 'name',
			caption: '用户名'
		}, {
			dataField: 'chAuthTag',
			caption:'身份'
		},{
			dataField: 'account',
			caption: '帐号'
		},
		{
			caption: '操作',
			cellTemplate: function(con, dat) {
				$("<a href='#' style='padding-right: 10px;'>编辑</a>").click(function() {
					App.getEventContext().redirect('#/expert-user/edit/' + dat.data.id);
					return false;
				}).appendTo($(con));

				$(con).dxDelete('expert-user', dat)
			}
		}
	],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		afterDataUpdate: function(formInstance, data) {
			//console.log(formInstance.geiEditor("#editor"));

		},
		items: [
		{
			itemType: "group",
			items: [{
				dataField:'userType',
				label:{text:'请选择'},
				editorType:'dxRadioGroup',
				validationRules: [{type: "required"}],
				editorOptions: {
				layout: "horizontal",
				valueExpr: 'value',
				dataSource: [{
					text: '专家',
					value: 'expert'
				}, {
					text: '达人',
					value: 'talent'
				}],
				onValueChanged: function(e) {
				//  var formInstance = App.getFormInstance();
				//  console.log(formInstance)
				//  let text = '专家姓名';
				//  if(e.value == 'talent'){
				//  	text = '达人姓名'
				//  }
				// formInstance.getEditor('userType').option('label',{text:text}) ;
				   	


				}
			}
			},{
					dataField: "account",
					label: {
						text: '姓名'
					},
					validationRules: [{
						type: "required"
					}]
				},{
					dataField:'authTag',
					editorType:'dxSelectBox',
					editorOptions:{
						dataSource: $.crudStore(API('restful?_model=user-auth-tag')),
						displayExpr: 'name',
						valueExpr: 'code'
					}
				},
				{
					dataField: "avatar",
					editorType: "ImageUploader",
					label: {
						text: '头像'
					},
					editorOptions: {
						single: true
					}

				},
				{
					dataField: "intro",
					label: {
						text: '个人简介'
					},
					editorType: "dxTextArea",
					editorOptions: {
						height: 90,
						autoResizeEnabled: false,

					}
				}
			]
		}]
	}

});



App.registerCrud({
	url: API('restful?_model=sys-produce'),
	route: 'producer',
	title: '生产商',
	capable: {
		create: true
	},
	buttons: [],
	columns: [{
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		dataField: 'name',
		caption: '名称'
	}, {
		dataField: 'chname',
		caption: '中文名称'
	}, {
		dataField: 'produceCode',
		caption: '生产商码'
	}, {
		caption: '操作',
		buttons: [{
			title: '编辑',
			url: '#/producer/edit/{{id}}'
		}]
	}],
	form: {
		items: [{
			dataField: 'produceCode',
			label: {
				text: '生产商码'
			},
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'name',
			label: {
				text: '名称'
			},
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'chname',
			label: {
				text: '中文名称'
			},
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'logo',
			label: {
				text: 'LOGO'
			},
			editorType: 'ImageUploader',
			editorOptions: {
				single: true
			}
		}]
	}
});



App.registerCrud({
	url: API('restful?_model=wine-focus-picture'),
	route: 'banner',
	title: '焦点图',
	capable: {
		create: true
	},
	buttons: [],
	columns: [{
		dataField: 'pic',
		caption: '图片',
		cellTemplate: function(c, ci) {
			$("<img src='" + ci.data.pic + "?imageView2/0/h/60'/>").appendTo(c);
		}
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		dataField: 'title',
		caption: '标题'
	}, {
		dataField: 'type',
		caption: '类型',
		cellTemplate: function(c, ci) {
			let text ='葡萄酒'
			switch(ci.value){
				case 'article':text='文章';break;
				case 'activity':text='活动'
			}
			c.text(text);
		}
	}, {
		dataField: 'weight',
		caption: '权重',
		cellTemplate: function(con, da) {
			$(con).dxWeight("focus", da);
		}
	}, {
		caption: '操作',
		cellTemplate: function(con, dat) {
			$("<a href='#' style='padding-right: 10px;'>编辑</a>").click(function() {
				App.getEventContext().redirect('#/banner/edit/' + dat.data.id);
				return false;
			}).appendTo($(con));

			$(con).dxDelete('wine-focus-picture', dat)
		}
	}],
	form: {
		beforeDataUpdate: function(formInstance, e) {
			e.data.obj_id = parseInt(e.data.obj_id);
		},
		items: [{
			dataField: 'title',
			label: {
				text: '标题'
			},
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'pic',
			label: {
				text: '封面图片'
			},
			editorType: 'ImageUploader',
			editorOptions: {
				single: true,
				imageWidth: 750,
				imageHeight: 608
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'type',
			label: {
				text: '类型'
			},
			validationRules: [{
				type: "required"
			}],
			editorType: 'dxRadioGroup',
			editorOptions: {
				layout: "horizontal",
				valueExpr: 'value',
				dataSource: [{
					text: '文章',
					value: 'article'
				}, {
					text: '葡萄酒',
					value: 'product'
				},{
					text:'活动',
					value:'activity'
				}],
				onValueChanged: function(e) {
					var formInstance = App.getFormInstance();

					// formInstance.updateData({obj_id: 0});

					if(e.value === 'article') {
						formInstance.getEditor('obj_id').option({
							dataSource: $.crudStore(API('simplelist?_model=cms-article'))
						});
					}else if(e.value === 'activity'){
						formInstance.getEditor('obj_id').option({
							dataSource: $.crudStore(API('simplelist?_model=activity'))
						});
					} else {
						formInstance.getEditor('obj_id').option({
							dataSource: $.crudStore(API('simplelist?_model=wine-product'))
						});
					}
				}
			}
		}, {
			dataField: 'obj_id',
			label: {
				text: '文章/葡萄酒/活动'
			},
			validationRules: [{
				type: "required"
			}],
			editorType: 'dxSelectBox',
			editorOptions: {
				dataSource: $.crudStore(API('restful?_model=cms-article')),
				showClearButton: true,
				searchEnabled: true,
				valueExpr: 'id',
				noDataText: '没有请求到数据',
				itemTemplate: function(data, index, $el) {
					if(data && data.chname && data.name) {
						$("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
					} else if(data && data.title) {
						$("<span>" + data.title + "</span>").appendTo($el);
					}else if(data && data.name){
						$("<span>" + data.name + "</span>").appendTo($el);
					}
				},
				displayExpr: function(data) {
					if(data && data.chname && data.name) {
						return data.chname + " (" + data.name + ")";
					} else if(data && data.title) {
						return data.title;
					} else if(data && data.name){
						return data.name
					}else{
						return ''
					}
				}
			}
		}]
	}
});




$(function() {

    let initApp = () => {
        var app = $.sammy('#content', function() {
            var app = this;

            console.log("handle routes");
            console.log(App.routes);

            $.each(App.routes, function(i, route) {
                var m = route.name.match(/[^\/]*/);
                app.get('#/' + route.name, function() {

                    var eventContext = this;

                    route.onLoad && route.onLoad.call(route, eventContext, $('#content'));

                    // $.get('template/' + m[0] + '.html', function(resp) {
                    //  $('#content').html(resp).dxInit();
                    //  $("#content").trigger("route.loaded", [eventContext])
                    // });
                });
            });

            // for(var i = 0; i < routes.length; i++) {
            //  (function(route) {
            //      var m = route.match(/[^\/]*/);
            //      app.get('#/' + route, function() {

            //          var eventContext = this;

            //          $.get('template/' + m[0] + '.html', function(resp) {
            //              $('#content').html(resp).dxInit();
            //              $("#content").trigger("route.loaded", [eventContext])
            //          });
            //      });
            //  })(routes[i]);
            // }

            console.log("handle pages");
            console.log(App.pages);
            $.each(App.pages, function(i, page) {
                $.crud($.extend({
                    app: app
                }, page));
            })

        });

        app.bind('changed', {}, function() {
            App.setEventContext(this);
        });
        app.run('#/product');
    }

    if (!localStorage.accessToken) {
		window.location.href = 'login.html';
		return;
	} else {

		$.ajax({
			headers: {
				Authorization: "bearer " + localStorage.accessToken
			},
			url: API('auth/me'),
			type: 'get',
			success: function(resp) {
				$(".app").show();

				var data = resp.data,
					type = data.userType;
				// if (data.userType === 'super' && data.account === 'admin') {
				// 	type = 'super';
				// }
				App.login(data);
console.log(resp)
				$(".admin-name").text(data.name);
				$(".auth-" + type).show();


				initApp();
			},
			error: function(resp) {
				window.location.href = 'login.html';

			}
		});
	}


    DevExpress.viz.currentTheme("generic.light");

    $("body").dxInit();

});